// std
#include <stdexcept>
#include <map>

#include "taskthread.h"

// app common
#include "log/logger.h"
#include "task.h"
#include "taskqueue.h"

namespace thread {

TaskThread::TaskThread(TaskQueue& tq):
  task_queue_(tq)
{
  MEMBER_DEBUG_LOG("[+/-]TaskQueue::ctor");
}

TaskThread::~TaskThread()
{
  MEMBER_DEBUG_LOG("[+/-]TaskQueue::dtor");
}

void TaskThread::Run()
{
  MEMBER_DEBUG_LOG("[+]TaskThread::Run");
  while(!this->stop())
  {
    if(!this->Action())
    {
      break;
    }
  }
  LOG( LOG_WARNING, "task thread(%lu) exit", pthread_self() );
  MEMBER_DEBUG_LOG("[-]TaskThread::Run");
}

bool TaskThread::Action()
{
  MEMBER_DEBUG_LOG("[+]TaskThread::Action");
  Task* tk = task_queue_.Pop();
  if (tk)
  {
    try
    {           // Do you want to pass some argument from the thread to
      tk->Execute(this, NULL); // the command ? if yes, override it
      tk->Release();     // release resource
      tk = NULL;
    }
    catch(const std::exception& e)
    {
      MEMBER_LOG( LOG_ERR, "Catch Exception: %s", e.what() );
    }
    catch(...)
    {
      MEMBER_LOG(LOG_ERR, "Catch unknown exception");
    }
  }
  MEMBER_DEBUG_LOG("[-]TaskThread::Action");
  return true;  // if false, indicate to tell the thread to exit
}

}

